package com.dd.stack.se.stream.concurrent;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * @Author liuxianmeng
 * @CreateTime 2025/9/3 17:01
 * @Description 类功能作用说明
 */
public class FutureTaskTest {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //futureTaskUse();
        joinMethodUse();
    }

    /**
     * 测试FutureTask的使用
     *
     * @throws InterruptedException
     * @throws ExecutionException
     */
    private static void futureTaskUse() throws InterruptedException, ExecutionException {
        FutureTask<Integer> futureTask = new FutureTask<Integer>(new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    System.out.println(Thread.currentThread().getName() + " Interrupted.");
                    throw new RuntimeException(e);
                }
                System.out.print(Thread.currentThread().getName() + ": ");
                return 100;
            }
        });
        Thread thread = new Thread(futureTask);
        thread.setName("FutureTask使用测试线程");
        thread.start();
        System.out.println(thread.getName() + " started.");
        Thread.sleep(1000);
        thread.interrupt();
        // FutureTask使用测试线程: 100
        System.out.println(futureTask.get());
    }

    /**
     * Join()方法的使用
     */
    private static void joinMethodUse() throws InterruptedException {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println(Thread.currentThread().getName() + ": 执行结束.");
            }
        });
        thread.setName("测试join方法的线程");
        thread.start();
        thread.join(); // 主线程等待thread线程执行结束
        System.out.println("主线程执行结束");
    }
}
